package cn.xuhang.nav.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cn.xuhang.nav.utils.WebUtils;
import cn.xuhang.nav.view.JsonView;

import com.google.gson.Gson;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.xuhang.nav.domain.NavItem;
import cn.xuhang.nav.service.NavItemService;

import org.springframework.web.servlet.ModelAndView;

@Controller("navController")
@RequestMapping("/nav")
public class NavItemController {
	@Autowired
	public NavItemService navService;
	
	Logger DEBUG = Logger.getLogger(NavItemController.class);
	
	@RequestMapping("/homePage.action")
	public String homePage(Model model, HttpServletRequest request){
		List<NavItem> items = this.navService.queryAllItems();
		model.addAttribute("navItems", items);
		model.addAttribute("realip", WebUtils.getRealIpAddress(request));
		DEBUG.debug(items);
		return "index";
	}
	
	@RequestMapping("/add.action")
	public String insertNavItem(NavItem item) throws IOException {
		this.navService.insertNavItem(item);
		return "redirect:/nav/homePage.action";
	}
	
	@RequestMapping("/fetchUrls.action")
	public JsonView fetchIconUrls(NavItem item, Model model) throws IOException {
		String url = item.getUrl();
		List<String> urls = this.navService.getIcon(url);
		urls.add(0, this.navService.getRootIconURL(url).toString());
		model.addAttribute("iconUrls", urls);
		return new JsonView(urls);
	}
	
	@RequestMapping("/fetchItemDetail.action")
	public JsonView fetchItemDetail(NavItem item, Model model){
		item = this.navService.queryNavItemById(item.getNavid());
//		model.addAttribute("navid", item.getNavid());
//		model.addAttribute("siteName", item.getSiteName());
//		model.addAttribute("imgSrc", item.getImgSrc());
//		model.addAttribute("url", item.getUrl());
		return new JsonView(item);
	}
	
	@RequestMapping("/update.action")
	public JsonView updateItem(NavItem item){
		this.navService.updateNavItem(item);
		return new JsonView(item);
	}
	
	@RequestMapping("/delete.action")
	public String deleteItem(Integer navid){
		this.navService.deleteNavItem(navid);
		return "";
	}
	
	@RequestMapping("/search.action")
	public JsonView search(String fuzzkw){
		
		return null;
	}
}
